<template>
  <div>
    <menu-bar
      :menus="subMenus"
      :current-path="currentPath"
      :tabs-class="tabsClass"
    />

    <refresh-list
      ref="refreshList"
      :enable-pull-refresh="false"      
      @pull-load="handlePullLoad"
    >
      <div class="panel"
        v-for="(item, index) in currentModules"
        :key="index"
      >
        <div class="panel-heading">
          <h4 class="panel-title">{{item.title}}</h4>
          <template v-if="isIndex">
            <template v-if="index === 0">
              <span class="rank" @click="toRank">
                <i class="fa fa-hot"></i>排行榜 <i class="fa fa-dropright"></i>
              </span>
            </template>
            <template v-else>
              <span class="panel-more" @click="toChannel(item.id)">
                查看更多<i class="fa fa-dropright"></i>
              </span>
            </template>
          </template>
        </div>
        <div class="panel-body">
          <template v-if="item.data">
            <video-item
              class="vi"
              v-for="(vi, vindex) in item.data"
              :key="vindex"
              :aid="vi.aid"
              :bvid="vi.bvid"
              :title="vi.title"
              :coverPath="vi.pic"
              :view="vi.play !== undefined ? vi.play : vi.stat.view"
              :danmaku="vi.video_review !== undefined ? vi.video_review : vi.stat.danmaku"
              :allParams="vi"
            />
          </template>
          <template v-else>
            <div class="tips" @click="reloadModule(index)">出错了，点击重试</div>
          </template>
        </div>
      </div>

    </refresh-list>
  </div>
</template>

<script>
import MenuBar from '@/components/menu-bar/MenuBar'
import { apiGetRanking, apiGetDynamic } from '@/api/channel'
import VideoItem from '@/components/video-item/VideoItem'
import RefreshList from '@/components/refresh-list/RefreshList'
export default {
  name: 'Channel',
  inject: ['routerConfig', 'rootTitle'],
  metaInfo () {
    return {
      title: this.title     
    }
  },
  components: {
    MenuBar,
    RefreshList,
    VideoItem
  },
  props: {
    id: {
      type: [Number, String],
      required: true
    },
    subid: {
      type: [Number, String]
    }
  },
  data () {
    return {
      tabsClass: 'sub-menu',
      currentPage: 1,
      totalPage: null,
      currentModules: []
    }
  },
  computed: {
    isIndex () {
      return this.id && !this.subid
    },
    title () {
      let word = this.rootTitle
      const id = this.id - 0
      const subid = this.subid ? this.subid - 0 : 0
      for (const c of this.routerConfig) {
        const { tid, sub, name } = c
        if (this.id && this.subid) {
          if (sub) {
            for (const subConfig of sub) {
              const subName = subConfig.name
              const subTid = subConfig.tid
              if (subid === subTid) {
                word = `${subName}-${name}-${word}`
                break
              }
            }
          }
        } else {
          if (id === tid) {
            word = `${name}-${word}`
            break
          }
        }
      }
      return word
    },
    currentPath () {
      return `/channel/${this.id}${this.subid ? ('/' + this.subid) : ''}`
    },
    subMenus () {
      const arr = []
      const id = this.id - 0
      for (const c of this.routerConfig) {
        const { tid, sub, hide } = c
        if (id === tid) {
          if (hide) {
            continue
          }
          arr.push({
            title: '推荐',
            id: tid,
            path: `/channel/${tid}`
          })
          for (const subConfig of sub) {
            const subTid = subConfig.tid
            const subHide = subConfig.hide
            const subName = subConfig.name
            if (!subHide) {
              arr.push({
                title: subName,
                id: subTid,
                path: `/channel/${tid}/${subTid}`
              })
            }
          }
          break
        }
      }
      return arr
    },
    modules () {
      let mods = []
      if (this.isIndex) {
        mods = this.subMenus.map(menu => {
          return {
            title: menu.title === '推荐' ? '热门推荐' : menu.title,
            id: menu.id,
            data: []
          }
        })
      } else {
        mods = [
          {
            title: '热门推荐',
            id: this.subid,
            data: []
          },
          {
            title: '最新视频',
            id: this.subid,
            data: []
          }
        ]
      }
      return mods
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler (to) {
        const { params: { id, subid } } = to
        if (this.checkUrl()) {
          this.resetData()
          if (id && subid) {
            this.initChannel()
          } else if (id) {
            this.initIndex()
          }
        }
      }
    }
  },
  methods: {
    checkUrl () {
      let flag = true
      const parentIndex = this.routerConfig.findIndex(config => config.tid === this.id - 0)
      if (parentIndex > -1) {
        const children = this.routerConfig[parentIndex].sub
        if (this.subid) {
          const childIndex = children.findIndex(cd => cd.tid === this.subid - 0)
          if (childIndex === -1) {
            this.$router.replace({ name: '404' })
            flag = false
          }
        }
      }
      return flag
    },
    resetData () {
      this.$refs.refreshList && this.$refs.refreshList.reset()
      this.listTimeout = null
      this.currentPage = 1
      this.totalPage = null
      this.currentModules = []
    },
    // 初始化频道推荐下的数据
    async initIndex () {
      const defaultMenus = this.subMenus.slice(0, 3)
      const results = defaultMenus.map(async menu => {
        const response = await apiGetRanking({
          rid: menu.id
        })
        return response
      })

      // 按次序输出
      for (const [index, result] of results.entries()) {
        const res = await result
        if (res) {
          // 请求成功解析数据
          const { code, data } = res
          if (code === 0 && data) {
            this.currentModules.push({
              title: this.modules[index].title,
              id: this.modules[index].id,
              data: data.slice(0, 4)
            })
          }
        } else {
          // 请求失败
          this.currentModules.push({
            title: this.modules[index].title,
            id: this.modules[index].id,
            data: null
          })
        }
      }
      this.currentPage = 2
      this.totalPage = this.subMenus.length
      this.$refs.refreshList.stopLoad()
    },
    // 初始化频道的其他栏目的数据
    async initChannel () {
      const results = this.modules.map(async (mod, index) => {
        let response = null
        if (index === 0) {
          response = await apiGetRanking({
            rid: this.subid
          })
        } else {
          response = await apiGetDynamic({
            id: this.id,
            subid: this.subid,
            pn: this.currentPage
          })
        }
        return response
      })
      // 按次序输出
      for (const [index, result] of results.entries()) {
        const res = await result
        if (res) {
          // 请求成功解析数据
          const { code, data } = res
          if (index === 0) {
            if (code === 0 && data) {
              this.currentModules.push({
                title: this.modules[index].title,
                id: this.modules[index].id,
                data: data.slice(0, 4)
              })
            }
          } else {
            const { archives, page: { size, count } } = data
            this.currentModules.push({
              title: this.modules[index].title,
              id: this.modules[index].id,
              data: archives
            })
            this.totalPage === null && (this.totalPage = Math.ceil(count / size))
          }
        } else {
          // 请求失败
          this.currentModules.push({
            title: this.modules[index].title,
            id: this.modules[index].id,
            data: null
          })
        }
      }
      this.$refs.refreshList.stopLoad()
    },
    // 获取推荐页面数据
    getIndexData (rid) {
      apiGetRanking({
        rid
      }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          this.currentModules.push({
            title: this.modules[this.currentPage].title,
            id: this.modules[this.currentPage].id,
            data: data.slice(0, 4)
          })
          if (this.currentPage === this.totalPage - 1) {
            this.$refs.refreshList.completeLoad()
          }
        }
      }).finally(() => {        
         this.$refs.refreshList.stopLoad()
      })
    },
    // 获取子频道页面数据
    getChannelData () {
      apiGetDynamic({
        id: this.id,
        subid: this.subid,
        pn: this.currentPage
      }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          const { archives, page: { count, size } } = data
          this.totalPage === null && (this.totalPage = Math.ceil(count / size))
          this.currentModules[1].data.push(...archives)
          if (this.currentPage === 4) {
            // this.listFinishedText = '只能到这里了，我们在客户端不见不散'
            this.$refs.refreshList.completeLoad()
          }
        }
      }).finally(() => {
        this.$refs.refreshList.stopLoad()
      })
    },
    // 页面到底部事件
    handlePullLoad () {
      clearTimeout(this.listTimeout)
      this.listTimeout = setTimeout(() => {
        if (!this.$refs.refreshList.isFinished()) {
          this.currentPage++
          if (this.isIndex) {
            this.getIndexData(this.modules[this.currentPage].id)
          } else {
            if (this.modules[1].data !== null) {
              this.getChannelData(this.modules[1].id)
            }
          }
        }
      }, 1000)
    },
    // 某一模块加载失败后点重新加载
    reloadModule (index) {
      if (this.isIndex || (!this.isIndex && index === 0)) {
        // 重新加载推荐页模块或者子频道下的热门推荐模块
        apiGetRanking({
          rid: this.currentModules[index].id
        }).then(res => {
          const { code, data } = res
          if (code === 0 && data) {
            this.currentModules[index].data = data.slice(0, 4)
          }
        })
      } else {
        // 重新加载子频道下的最新视频模块
        this.currentPage = 1
        this.currentModules[index].data = []
        this.getChannelData()
      }
    },
    toRank () {
      this.$router.push({ name: 'rank', params: { id: this.id } })
    },
    toChannel (subid) {
      this.$router.push({ name: 'channel', params: { id: this.id, subid } })
    }
  }
}
</script>

<style lang="scss" scoped>
  .tips{
    font-size: 16px;
    text-align: center;
  }
  .sub-menu{
    position: sticky;
    top: 84px;
    z-index: 99;
  }
  .rank {
    color: #ffa726;
    font-size: 14px;
    .fa {
      font-size: 14px;
    }
  }
  .sub-menu ::v-deep .van-tab{
    flex-basis: 100/4*1% !important;
  }

  .panel{
    margin: {
      top: 20px;
      bottom: 20px;
    }
    &:first-child {
      margin-top: 10px;
    }
    &-heading{
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 5px 10px;
    }
    &-title{
      margin: 0;
      font-size: 15px;
      color: $color-text-regular;
      font-weight: 500;
    }
    &-more{
      color: $color-text-secondary;
      font-size: 14px;
      .fa{
        font-size: 14px;
      }
    }
    &-body{
      display: flex;
      flex-wrap: wrap;
      padding: 5px;
      .vi{
        width: 50%;
        box-sizing: border-box;
      }
    }
  }
</style>
